<template>
  <div class="exam-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试管理</span>
          <el-button type="primary" @click="fetchPaperList">
            刷新
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="80px">
        <el-form-item label="课程">
          <el-select
            v-model="queryForm.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            style="width: 200px"
            @change="handleQuery"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入试卷名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      
      <!-- 试卷表格 -->
      <el-table
        v-loading="loading"
        :data="paperList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="试卷名称" min-width="200" />
        <el-table-column label="所属课程" width="150">
          <template #default="{ row }">
            {{ getCourseName(row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长(分钟)" width="120" />
        <el-table-column label="开始时间" width="180">
          <template #default="{ row }">
            {{ row.startTime ? formatDateTime(row.startTime) : '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="{ row }">
            {{ row.endTime ? formatDateTime(row.endTime) : '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="考试状态" width="120">
          <template #default="{ row }">
            <el-tag v-if="!row.startTime || !row.endTime" type="info">未设置时间</el-tag>
            <el-tag v-else-if="getPaperStatus(row) === 'not_started'" type="info">未开始</el-tag>
            <el-tag v-else-if="getPaperStatus(row) === 'in_progress'" type="warning">进行中</el-tag>
            <el-tag v-else-if="getPaperStatus(row) === 'finished'" type="success">已结束</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'draft'" type="info">草稿</el-tag>
            <el-tag v-else-if="row.status === 'published'" type="success">已发布</el-tag>
            <el-tag v-else type="info">草稿</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="参加人数" width="100">
          <template #default="{ row }">
            {{ getExamCount(row.id) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380" fixed="right">
          <template #default="{ row }">
            <el-space wrap>
              <el-button
                link
                :type="row.status === 'published' ? 'warning' : 'success'"
                size="small"
                @click="handleTogglePublish(row)"
              >
                {{ row.status === 'published' ? '取消发布' : '发布' }}
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="handleViewRecords(row.id)"
              >
                考试记录
              </el-button>
              <el-button
                link
                type="success"
                size="small"
                @click="handleViewStatistics(row.id)"
              >
                统计信息
              </el-button>
              <el-button
                link
                type="info"
                size="small"
                @click="handleSetExamTime(row)"
              >
                设置考试时间
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 统计信息对话框 -->
    <el-dialog
      v-model="showStatisticsDialog"
      title="考试统计信息"
      width="60%"
    >
      <div v-if="statistics" class="statistics-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="试卷名称">{{ statistics.paperName }}</el-descriptions-item>
          <el-descriptions-item label="所属课程">{{ getCourseName(statistics.courseId) }}</el-descriptions-item>
          <el-descriptions-item label="参加人数">{{ statistics.totalCount }} 人</el-descriptions-item>
          <el-descriptions-item label="已完成">{{ statistics.finishedCount }} 人</el-descriptions-item>
          <el-descriptions-item label="进行中">{{ statistics.inProgressCount }} 人</el-descriptions-item>
          <el-descriptions-item label="未开始">{{ statistics.notStartedCount }} 人</el-descriptions-item>
          <el-descriptions-item label="平均分">
            <span :class="getScoreClass(statistics.averageScore)">
              {{ statistics.averageScore.toFixed(2) }} 分
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="最高分">
            <span class="score-excellent">{{ statistics.maxScore.toFixed(2) }} 分</span>
          </el-descriptions-item>
          <el-descriptions-item label="最低分">
            <span class="score-fail">{{ statistics.minScore.toFixed(2) }} 分</span>
          </el-descriptions-item>
          <el-descriptions-item label="及格人数">
            {{ statistics.passCount }} 人（{{ ((statistics.passCount / statistics.finishedCount) * 100).toFixed(1) }}%）
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider>成绩分布</el-divider>
        <div class="score-distribution">
          <div class="distribution-item">
            <span class="label">90-100分：</span>
            <span class="value">{{ statistics.score90to100 }} 人</span>
          </div>
          <div class="distribution-item">
            <span class="label">80-89分：</span>
            <span class="value">{{ statistics.score80to89 }} 人</span>
          </div>
          <div class="distribution-item">
            <span class="label">70-79分：</span>
            <span class="value">{{ statistics.score70to79 }} 人</span>
          </div>
          <div class="distribution-item">
            <span class="label">60-69分：</span>
            <span class="value">{{ statistics.score60to69 }} 人</span>
          </div>
          <div class="distribution-item">
            <span class="label">60分以下：</span>
            <span class="value">{{ statistics.scoreBelow60 }} 人</span>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 设置考试时间对话框 -->
    <el-dialog
      v-model="showExamTimeDialog"
      title="设置考试时间"
      width="500px"
    >
      <el-form
        ref="examTimeFormRef"
        :model="examTimeForm"
        :rules="examTimeFormRules"
        label-width="100px"
      >
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="examTimeForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="examTimeForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showExamTimeDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveExamTime">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 发布考试对话框 -->
    <el-dialog
      v-model="showPublishDialog"
      title="发布考试"
      width="600px"
    >
      <el-form label-width="100px">
        <el-form-item label="发布方式">
          <el-radio-group v-model="publishForm.publishType">
            <el-radio :label="'all'">全部发布</el-radio>
            <el-radio :label="'selected'">指定学生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="publishForm.publishType === 'selected'" label="选择学生">
          <el-select
            v-model="publishForm.selectedStudentIds"
            multiple
            filterable
            placeholder="请选择学生"
            style="width: 100%"
            :loading="loadingStudents"
          >
            <el-option
              v-for="student in studentOptions"
              :key="student.id"
              :label="`${student.realName || student.username} (${student.username})`"
              :value="student.id"
            />
          </el-select>
          <div style="margin-top: 8px; color: #909399; font-size: 12px;">
            已选择 {{ publishForm.selectedStudentIds.length }} 名学生
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPublishDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmPublish">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getPaperList, publishPaper, unpublishPaper, updateExamTime, type PaperInfo } from '../../api/paper'
import { getMyCourses, getCourseList, getCourseStudents, type CourseInfo } from '../../api/course'
import { getPaperExamRecords, type ExamRecord } from '../../api/exam'
import { useUserStore } from '../../store/user'
import type { UserInfo } from '../../api/course'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const paperList = ref<PaperInfo[]>([])
const courseOptions = ref<CourseInfo[]>([])
const examRecordsMap = ref<Record<number, ExamRecord[]>>({})
const showStatisticsDialog = ref(false)
const statistics = ref<any>(null)
const showExamTimeDialog = ref(false)
const examTimeFormRef = ref<FormInstance>()
const examTimeForm = reactive({
  paperId: null as number | null,
  startTime: '',
  endTime: ''
})

const showPublishDialog = ref(false)
const currentPublishPaper = ref<PaperInfo | null>(null)
const studentOptions = ref<UserInfo[]>([])
const loadingStudents = ref(false)
const publishForm = reactive({
  publishType: 'all' as 'all' | 'selected',
  selectedStudentIds: [] as number[]
})

const examTimeFormRules: FormRules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

const queryForm = reactive({
  name: '',
  courseId: null as number | null
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 获取试卷列表
const fetchPaperList = async () => {
  loading.value = true
  try {
    const res = await getPaperList({
      name: queryForm.name || undefined,
      courseId: queryForm.courseId || undefined,
      teacherId: userStore.isAdmin ? undefined : (userStore.userId ? parseInt(userStore.userId) : undefined),
      page: pagination.page,
      size: pagination.size
    })
    
    paperList.value = res.data.data || []
    pagination.total = res.data.total || 0
    
    // 加载每个试卷的考试记录数量
    for (const paper of paperList.value) {
      await loadExamCount(paper.id)
    }
  } catch (error) {
    ElMessage.error('获取试卷列表失败')
  } finally {
    loading.value = false
  }
}

// 加载考试记录数量
const loadExamCount = async (paperId: number) => {
  try {
    const res = await getPaperExamRecords(paperId)
    examRecordsMap.value[paperId] = res.data || []
  } catch (error) {
    examRecordsMap.value[paperId] = []
  }
}

// 获取课程列表
const fetchCourseList = async () => {
  try {
    if (userStore.isAdmin) {
      const res = await getCourseList({ page: 1, size: 1000 })
      courseOptions.value = res.data.data || []
    } else {
      const res = await getMyCourses()
      courseOptions.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 获取课程名称
const getCourseName = (courseId: number) => {
  const course = courseOptions.value.find(c => c.id === courseId)
  return course ? course.name : '未知'
}

// 获取试卷状态
const getPaperStatus = (paper: PaperInfo) => {
  if (!paper.startTime || !paper.endTime) {
    return 'not_started' // 未设置时间
  }
  
  const now = new Date()
  const startTime = new Date(paper.startTime)
  const endTime = new Date(paper.endTime)
  
  if (now < startTime) {
    return 'not_started'
  } else if (now >= startTime && now <= endTime) {
    return 'in_progress'
  } else {
    return 'finished'
  }
}

// 获取考试人数
const getExamCount = (paperId: number) => {
  return examRecordsMap.value[paperId]?.length || 0
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchPaperList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.courseId = null
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchPaperList()
}

// 当前页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchPaperList()
}

// 查看考试记录
const handleViewRecords = (paperId: number) => {
  router.push({
    name: 'ExamRecords',
    params: { paperId: paperId.toString() }
  })
}

// 发布/取消发布
const handleTogglePublish = async (row: PaperInfo) => {
  try {
    if (row.status === 'published') {
      // 取消发布
      await ElMessageBox.confirm('确定要取消发布该试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await unpublishPaper(row.id)
      ElMessage.success('取消发布成功')
      fetchPaperList()
    } else {
      // 发布：打开选择学生的对话框
      currentPublishPaper.value = row
      publishForm.publishType = 'all'
      publishForm.selectedStudentIds = []
      
      // 加载该课程的学生列表
      await loadCourseStudents(row.courseId)
      
      showPublishDialog.value = true
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 加载课程学生列表
const loadCourseStudents = async (courseId: number) => {
  loadingStudents.value = true
  try {
    const res = await getCourseStudents(courseId)
    studentOptions.value = res.data || []
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    studentOptions.value = []
  } finally {
    loadingStudents.value = false
  }
}

// 确认发布
const handleConfirmPublish = async () => {
  if (!currentPublishPaper.value) return
  
  if (publishForm.publishType === 'selected' && publishForm.selectedStudentIds.length === 0) {
    ElMessage.warning('请至少选择一名学生')
    return
  }
  
  try {
    const studentIds = publishForm.publishType === 'selected' ? publishForm.selectedStudentIds : undefined
    await publishPaper(currentPublishPaper.value.id, studentIds)
    ElMessage.success('发布成功')
    showPublishDialog.value = false
    fetchPaperList()
  } catch (error: any) {
    ElMessage.error(error.message || '发布失败')
  }
}

// 查看统计信息
const handleViewStatistics = async (paperId: number) => {
  try {
    const paper = paperList.value.find(p => p.id === paperId)
    if (!paper) return
    
    const records = examRecordsMap.value[paperId] || []
    const finishedRecords = records.filter(r => r.status === 'finished' && r.totalScore !== null)
    
    const scores = finishedRecords.map(r => r.totalScore!).filter(s => s !== null)
    
    const stats = {
      paperId: paper.id,
      paperName: paper.name,
      courseId: paper.courseId,
      totalCount: records.length,
      finishedCount: finishedRecords.length,
      inProgressCount: records.filter(r => r.status === 'in_progress').length,
      notStartedCount: records.filter(r => r.status === 'not_started').length,
      averageScore: scores.length > 0 ? scores.reduce((a, b) => a + b, 0) / scores.length : 0,
      maxScore: scores.length > 0 ? Math.max(...scores) : 0,
      minScore: scores.length > 0 ? Math.min(...scores) : 0,
      passCount: scores.filter(s => s >= 60).length,
      score90to100: scores.filter(s => s >= 90 && s <= 100).length,
      score80to89: scores.filter(s => s >= 80 && s < 90).length,
      score70to79: scores.filter(s => s >= 70 && s < 80).length,
      score60to69: scores.filter(s => s >= 60 && s < 70).length,
      scoreBelow60: scores.filter(s => s < 60).length
    }
    
    statistics.value = stats
    showStatisticsDialog.value = true
  } catch (error) {
    ElMessage.error('获取统计信息失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 设置考试时间
const handleSetExamTime = (row: PaperInfo) => {
  examTimeForm.paperId = row.id
  if (row.startTime) {
    examTimeForm.startTime = row.startTime.replace(' ', 'T')
  } else {
    examTimeForm.startTime = ''
  }
  if (row.endTime) {
    examTimeForm.endTime = row.endTime.replace(' ', 'T')
  } else {
    examTimeForm.endTime = ''
  }
  showExamTimeDialog.value = true
}

// 保存考试时间
const handleSaveExamTime = async () => {
  if (!examTimeFormRef.value) return
  
  await examTimeFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (!examTimeForm.paperId) return
    
    try {
      await updateExamTime(examTimeForm.paperId, {
        startTime: examTimeForm.startTime,
        endTime: examTimeForm.endTime
      })
      ElMessage.success('设置成功')
      showExamTimeDialog.value = false
      fetchPaperList()
    } catch (error: any) {
      ElMessage.error(error.message || '设置失败')
    }
  })
}

// 获取得分样式类
const getScoreClass = (score: number) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

onMounted(() => {
  fetchCourseList()
  fetchPaperList()
})
</script>

<style scoped>
.exam-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-pass {
  color: #409eff;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}

.statistics-content {
  padding: 10px 0;
}

.score-distribution {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.distribution-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.distribution-item .label {
  font-weight: bold;
  color: #606266;
}

.distribution-item .value {
  color: #409eff;
  font-weight: bold;
}
</style>

